import React, { useEffect } from "react";
import { Modal, NavBar, Toast, Image as MyImage } from "antd-mobile";
import { useLocation, useNavigate } from "react-router-dom";
import $fetch from "../../../utils/app/$fetch";
import $reducer from "../../../utils/app/$reducer";
import { ReactComponent as CoreIcon } from '../../../asset/imgs/core.svg';
import "./style.scss";

const iconColor = getComputedStyle(document.documentElement)
  .getPropertyValue('--logoColor')
  .trim();

const PageCore = () => {
  const location: any = useLocation();
  const navigate: any = useNavigate();
  const customerPoint = location?.state?.customerPoint;

  let closeModal: any;

  const initState: any = {
    currentCore: customerPoint,
    coreList: [],
    visible: false,
    exchangeGoodsId: "",
  };

  const [state, dispatch] = $reducer({ ...initState });

  useEffect(() => {
    initPage();
  }, []);

  useEffect(() => {
    if (state?.coreList?.length > 0) {
      state?.coreList.forEach((item: any) => {
        const img: any = new Image();
        img.src = item?.goodsPhoto;
      });
    }
  }, [state?.coreList]);

  const initPage = async () => {
    const res: any = await $fetch("/customerPoint/customerPointDetail");
    dispatch({ coreList: res });
  };

  const handleSubmit = async (exchangeGoodsId: any) => {
    try {
      const result: any = await $fetch(
        `/customerPoint/customerPointExchange/${exchangeGoodsId}`,
        {},
        { loading: false, method: "post", noGroupId: "no" }
      );
      if (result?.data !== null) {
        Toast.show("兑换成功");
        const res: any = await $fetch(
          "/customerPoint/customerPointInf",
          {},
          { loading: false, noGroupId: "no" }
        );
        dispatch({ currentCore: res?.customerPoint });
      }
      closeModal();
    } catch (error) {
      closeModal();
    }
  };

  const showModal = (exchangeGoodsId: any) => {
    closeModal = Modal.show({
      content: "确认兑换该商品?",
      actions: [
        {
          key: "ok",
          text: "确认",
          primary: true,
          onClick: () => handleSubmit(exchangeGoodsId),
        },
        { key: "cancel", text: "取消", onClick: () => closeModal() },
      ],
    }).close;
  };

  return (
    <div className="Container_Core_List">
      <NavBar
        style={{
          "--border-bottom": "1px #eee solid",
        }}
        onBack={() => {
          // window.history.go(-1);
          navigate("/home", { state: { current: "personal" } });
        }}
      >
        积分
      </NavBar>
      <section>
        <div className="that_top">
          <div className="icon_core">
            <CoreIcon width='.53rem' height='.53rem' fill={iconColor}/>
            <div>
              我的积分: <span>{state?.currentCore || 0}</span>
            </div>
          </div>
          <div
            className="item_record"
            onClick={() => {
              navigate("/core/record");
            }}
          >
            兑换记录
          </div>
        </div>
        <ul className="that_content">
          {state?.coreList?.map((item: any) => {
            return (
              <li
                key={item?.goodsId}
                onClick={() => {
                  showModal(item?.goodsId);
                }}
              >
                <MyImage
                  src={item?.goodsPhoto}
                  fit="cover"
                  lazy={true}
                  width="4.27rem"
                  height="4.27rem"
                />
                <div className="item_content">
                  <div className="name">{item?.goodsName}</div>
                  <div className='core_wraper'>
                    <CoreIcon width='.53rem' height='.53rem' fill={iconColor}/>
                    <div className="icon_core">{item?.goodsPoints}</div>
                  </div>
                </div>
              </li>
            );
          })}
        </ul>
      </section>
    </div>
  );
};

export default PageCore;
